package cn.fuxi2022.accounts.register.service.impl;

import cn.fuxi2022.accounts.register.service.WeChatQR;
import cn.fuxi2022.core.exception.SmartGroupException;
import cn.fuxi2022.qiniu.utils.QiNiuUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;

@Service
public class WeChatQRImpl implements WeChatQR {

    @Autowired
    private WxMpService wxMpService;

    /**
     * 微信生成的二维码的后缀名
     */
    private static final String TYPE = ".jpg";

    @Override
    public String getQR(String activityId, Long expireSeconds) {
        // 将时间从毫秒转化为秒
        long temp = Math.round(expireSeconds * 1.0 / 1000L);
        // 向下取整
        double expireSecondsDouble = Math.rint(temp);
        int intValue = new BigDecimal(expireSecondsDouble).setScale(0, RoundingMode.DOWN).intValue();

        // 获取微信二维码临时ticket
        WxMpQrCodeTicket ticket;
        try {
            ticket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(activityId, intValue);
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new SmartGroupException("微信签到二维码生成失败");
        }

        // 获取微信二维码
        File file;
        try {
            file = wxMpService.getQrcodeService().qrCodePicture(ticket);
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new SmartGroupException("获取微信签到二维码失败");
        }

        // 将文件上传，返回图片二维码链接
        return QiNiuUtils.uploadFileFromQiniu(file, QiNiuUtils.IMAGE_USER_PATH, TYPE);
    }
}
